package geektime.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 利用传统io（bio）演示服务器
 */
public class ServerDemo extends Thread {

    private ServerSocket serverSocket;

    private ExecutorService executor;

    public static void main(String[] args) {
        // 创建一个服务器并启动
        ServerDemo server = new ServerDemo();
        server.start();
    }

    @Override
    public void run() {
        try {
            // 服务端启动时绑定端口9999
            serverSocket = new ServerSocket(9999);
            // 创建一个核心线程数为10的线程池，用来处理客户端的请求
            executor = Executors.newFixedThreadPool(10);

            while (true) {
                // 监听客户端的连接，并创建socket进行处理
                Socket socket = serverSocket.accept();
                // 模拟向客户端发送信息
//                SendMessage sendMessage = new SendMessage(socket);
//                executor.execute(sendMessage);
                // 模拟接收客户端的信息
                ReceiveMessage receiveMessage = new ReceiveMessage(socket);
                executor.execute(receiveMessage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 创建一个向客户端发送信息的类
     */
//    class SendMessage extends Thread {
//        private Socket socket;
//
//        public SendMessage(Socket socket) {
//            this.socket = socket;
//        }
//
//        @Override
//        public void run() {
//            try(PrintWriter out = new PrintWriter(socket.getOutputStream())) {
//                out.print("Hello world");
//                out.flush();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 创建一个接收客户端消息的类
     */
    class ReceiveMessage extends Thread {
        private Socket socket;

        public ReceiveMessage(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                bufferedReader.lines().forEach(System.out::println);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
